<template>
  <el-card class="app-container">

    
    <div>
      <div class="itemTitle">课程管理</div>
      <div class="search">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-col :span="5">
            <el-form-item label="课程名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入课程名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <div class="content">
        <div class="ct-btns">
          <el-button type="primary" @click="handleAdd" v-hasPermi="['edu:course:add']">新增</el-button>
        </div>
        <div class="ct-table">
          <elTables :table-data="tableData" :columns="tableColumns" :totalLength="total" :currentPage="queryParams.pageNum"
            :handle-current-change="handleCurrentChange" isPagin :curHeight="tableHeight" />
        </div>
      </div>
    </div>
    <!-- 添加或修改课程管理信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body @close="cancel" class="dialog-form">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-col :span="12">
          <el-form-item label="课程名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入课程名称" :readonly="!isEdit" :disabled="!isEdit" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属科目" prop="type">
            <el-select v-model="form.type" placeholder="请选择所属科目" :readonly="!isEdit" :disabled="!isEdit">
              <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件" prop="file">
            <el-upload
              ref="uploadRef"
              :headers="upload.headers" 
              :action="upload.url"
              :class="isEdit?'upload-demo':'hide upload-demo'"
              drag
              :on-success="handleFileSuccess"
              :on-remove="handleFileRemove"
              multiple
              :file-list="fileLists"
              :disabled="!isEdit"
              :limit="1"
              :on-exceed="handleExceed"
              :on-preview="handlePreview"
              :before-upload="beforeUploadAUDIO"
              accept=".mp4,.ogg,.flv,.avi,.wmv,.pdf,.rmvb,.mov,.PDF"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">
                <span>提示：</span>
                <div class="tip-content">
                  <span>①仅支持上传PDF文件及格式为mp4,rmvb,flv,wmv,avi,ogg,mov的视频文件。</span>
                  <span>②文件大小不超过200M。</span>
                </div>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容简介" prop="profiles">
            <el-input v-model="form.profiles" type="textarea" placeholder="请输入内容简介" :readonly="!isEdit"
              :disabled="!isEdit" :rows="3" :maxlength="300" :show-word-limit="true" />
          </el-form-item>
        </el-col>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPlay" class="file-preview" title="预览">
      <PDF v-if="fileType=='pdf'" ref="pdf" v-for="i in numPages" :key="i" :src="fileUrl" :page="i" />
      <video v-else :src="fileUrl" controls autoplay class="video" width="100%" id="videoPlay"></video>
    </el-dialog>
    <!-- <PDF
      :page="pageNum"
      :src="fileUrl"
      @progress="loadedRatio = $event"
      @num-pages="pageTotalNum = $event"
    ></PDF> -->
  </el-card>
</template>

<script>
const defaultQueryParams = {
  pageNum: 1,
  pageSize: 10,
};
import { getToken } from "@/utils/auth";
import { pageCourse, listCourse, getCourse, delCourse, addCourse, updateCourse, exportCourse, downImportTemplate } from "@/api/edu/course";
import PDF from "vue-pdf";
export default {
  name: "Course",
  components: { PDF },
  data() {
    return {
      fileUrl:"",
      pageNum:0,
      numPages:0,
      pdfUrl:'',
      pageTotalNum:'',
      loadedRatio:0,
      dialogPlay:false,
      videoUrl:'',
      fileType:'',
      videoDuration:'',
      typeOptions:[],
      fileLists:[],
      tableHeight: 0,
      isEdit: false,
      dialogFormVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:process.env.VUE_APP_BASE_API + "/common/upload",
      },
      tableData: [],
      // 查询参数
      queryParams: {
        ...defaultQueryParams,
        // 所属科目字典
        typeOptions: [],

        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "课程名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "所属科目不能为空", trigger: "change" }
        ],
        file: [
          { required: true, message: "附件不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      },
      tableColumns: [
        { key: "name", title: "课程名称" },
        { key: "type", title: "所属科目",render:(h,params) => {
          return h('span',{},
            this.typeOptions.find(_ => _.dictValue == params.row.type)?.dictLabel,
          )
        }},
        { key: "createName", title: "创建人" },
        { key: "createTime", title: "创建时间" },
        {
          title: "操作",
          align: "center",
          fixed: 'right',
          width: 200,
          render: (h, params) => {
            return h("div", [
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["edu:course:info"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 2)
                    },
                  },
                },
                "查看"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["edu:course:edit"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 1);
                    },
                  },
                },
                "编辑"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["edu:course:remove"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleDelete(params.row)
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ]

    };
  },
  created() {
    this.getPage();
    this.getDicts("course_subject").then(response => {
      this.typeOptions = response.data;
    });
  },
  mounted() {
    this.$nextTick(() => {
      this.getTableHeight();
    })
  },
  methods: {
    getNumPages() {
      let loadingTask = PDF.createLoadingTask(this.fileUrl);
      loadingTask.promise
        .then((pdf) => {
          this.videoDuration = this.numPages = pdf.numPages;
          console.log('this.numPages',this.numPages);
        })
        .catch((err) => {
          console.error('pdf 加载失败', err);
        });
    },
    beforeUploadAUDIO(file){
      console.log('file',file,this.pageTotalNum);
      if(file.type=='application/pdf'){
        this.fileType='pdf';
      }else{
        this.fileType='video';
        let _URL = window.URL || window.webkitURL;
        let url = _URL.createObjectURL(file);
        let audioElement = new Audio(url);
        let playTime=0;
        audioElement.addEventListener('loadedmetadata',() => {
          playTime = Math.ceil(audioElement.duration); //playTime就是当前视频长度
          this.videoDuration=playTime;
          console.log('playTime',playTime,this.videoDuration);
        })
      }
    },
    handlePreview(file){
      console.log('file',file,this.form,JSON.parse(this.form.file));
      this.dialogPlay=true;
      this.fileUrl=file.response.url;
      const suffix = this.fileUrl.substring(this.fileUrl.lastIndexOf('.') + 1).toLocaleLowerCase();
      console.log('suffix',suffix)
      if(this.fileType=='pdf' || suffix=='pdf'){
        this.getNumPages();
        this.fileType='pdf';
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`);
    },
    getTableHeight() {
      let height = document.getElementsByClassName('ct-table')[0].clientHeight;
      this.tableHeight = height - 40;
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getPage();
    },
    /** 查询课程管理信息列表 */
    getPage() {
      this.loading = true;
      pageCourse(this.queryParams).then(response => {
        this.tableData = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 所属科目字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 取消按钮
    cancel() {
      this.$refs.uploadRef.clearFiles();
      this.fileLists=[];
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        type: null,
        profiles: null,
        file: null,
        factoryId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        createDept: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPage();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isEdit = true;
      this.fileLists=[];
      this.title = "新增课程";
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      if (type == 1) {
        this.isEdit = true;
        this.title = "编辑课程信息";
      } else {
        this.isEdit = false;
        this.title = "查看课程信息";
      }
      this.reset();
      const id = row.id || this.ids;
      getCourse(id).then(response => {
        this.form = response.data;
        this.fileLists=JSON.parse(this.form.file);
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.file=this.fileLists&&this.fileLists.length>0?JSON.stringify(this.fileLists):"";
      this.form.courseTimer=this.videoDuration;
      console.log('videoDuration',this.form,this.videoDuration);
      this.$refs["form"].validate(valid => {
        console.log('this.form',this.form,this.$refs);
        if (valid) {   
          if (this.form.id != null) {
            updateCourse(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.$refs.uploadRef.clearFiles();
              this.open = false;
              this.getPage();
            });
          } else {
            addCourse(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.$refs.uploadRef.clearFiles();
              this.open = false;
              this.getPage();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        let data
        if (Array.isArray(ids)) {
          data = ids
        } else {
          data = [ids]
        }
        return delCourse(data);
      }).then(() => {
        this.getPage();
        this.msgSuccess("删除成功");
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleFileSuccess(response, file, fileList){
      console.log('fileList',fileList);
      if(response.code==200){
        this.fileUrl=response.url;
        if(this.fileType='pdf'){
          this.getNumPages();
        }
      }
      this.fileLists=fileList;
      console.log('this.fileLists',this.fileLists);
      if(this.fileLists&&this.fileLists.length>0){
        console.log('inin')
        this.$refs.form.clearValidate('file');
      }
    },
    handleFileRemove(file, fileList){
      this.fileLists=fileList;
    },
  }
};
</script>
<style lang="scss" scoped>
.upload-demo ::v-deep .el-upload__tip{
  display:flex;
  line-height:20px;
  .tip-content{
    display: flex;
    flex-direction: column;
    >span{
      line-height:20px;  
    }
  }
}
.hide ::v-deep {
  .el-upload--text,.el-upload__tip{
    display: none;
  }
}
</style>  